/**
* Azpiration Common Javascript Function (ACJF)
*
* @author      Dhanny Kosasih <dhanny.kosasih@gmail.com>
* @version     0.1
* @copyright   Azpiration 2008
* @filename    gui-function.js
*/

/**
* method for showing window popup
*/
var windows_collection = new Array();
var windows_name = new Array();
var window_index = 0;
function showPopup(url_address, window_name, form_width, form_height, modal) {
    window_index++;
	if (url_address.charAt(0) == "/") {
		url_address = _BASE_PATH + url_address;
	}
    var backdrop_modal = 'static';
    if (!modal && modal != undefined) backdrop_modal = false;
    jQuery(document.body).css("overflow", "none");
    html_component = buildPopupHtml(url_address, window_index, window_name, form_width, form_height);
    jQuery(document.body).append(html_component);

    jQuery('#popupWindow' + window_index).modal({
        backdrop: backdrop_modal,
        keyboard: false
    });
}

function buildPopupHtml(url_address, window_index, window_name, form_width, form_height) {
    var html_component =
                    '<!--[if lte IE 8]>'
                    + '<style>'
                    + '#popupWindow' + window_index + ' .modal-dialog  {width:' + form_width + 'px; height:' + form_height + 'px; margin:0 auto;} '
                    + '.modal-header {height:40px !important;} '
                    + '.modal-dialog {margin:20px auto !important;} '
                    + '</style>'
                    + '<![endif]-->'
        
                    + '<style type="text/css">'                                        
                    + '@media screen and (min-width: 768px) {#popupWindow' + window_index + ' .modal-dialog  {width:' + form_width + 'px;height:' + form_height + 'px; margin:0 auto;}}'
                    + '</style>'
                    
                    + '<div class="modal fade" id="popupWindow' + window_index + '" tabindex="-1" role="dialog" aria-labelledby="popupWindowLabel' + window_index + '" aria-hidden="true">'
                    + '<div class="modal-dialog">'
                    + '<div class="modal-content panel-default">'
                    + '<div class="modal-header panel-heading">'
                    + '<input type="button" value="&times;" class="close" data-dismiss="modal" aria-hidden="true" onblur="removePopupWindow(\'popupWindow' + window_index + '\')" >'                    
                    + '<h4 class="modal-title" id="popupWindowLabel' + window_index + '">' + window_name + '</h4>'
                    + '</div>'
                    + '<div class="modal-body" style="margin:0 auto;padding:5px;">'
                    + '<iframe src="' + url_address + '" frameborder="0" style="overflow: visible;" width="' + (form_width - 10) + '" height="' + form_height  + '"></iframe>'
                    + '</div>'
                    + '</div>'
                    + '</div>'
                    + '</div>';
                
    return html_component;
}

/**
* method yang dipanggil ketika popup dipilih
*/

/** versi sebelum di ubah
function popupSelect(table_id, obj_data) {
	eval(obj_data.CallbackFunction + "(table_id, obj_data);");
}
*/
function popupSelect(table_id, obj_data) {
	jQuery(".close").trigger("click");
	eval(obj_data.CallbackFunction + "(table_id, obj_data);");
}

/**
* test function, to knowing is window can call opener or top
*/
function testFunction() {
    // test function, to knowing is window can call opener or top
    return true;
}

/**
* method for close popup window
*/
function closePopupWindow(popup_index) {
    jQuery(".close").trigger("click");
}

/**
* method for remove popup window
*/
/**
function removePopupWindow(element_id) {    
    if (element_id == '') {
        jQuery("#popupWindow" + window.window_index).remove();
        jQuery(".modal-backdrop").attr("class", "");
    } else {
        jQuery("#" + element_id).remove();
    }
    jQuery(document.body).css("overflow", "visible");
}
*/
function removePopupWindow(element_id) {
    jQuery("#poupWindow0").remove();
    jQuery(document.body).css("overflow", "visible");
	// jQuery('#winpopup').remove();
	// jQuery('.modal-backdrop fade in').remove();
}

/**
* method for showing div popup
*/
function showDivPopup(content, window_name, form_width, form_height) {
    //var win = new Window({className: "dialog",  width:350, height:400, zIndex: 100, resizable: true, title: window_name, draggable:true, wiredDrag: true})

    if (content == '') {
        // generate loading gif
        content = "<div width='" + form_width + "' height='" + form_height + "' style='text-align:center'><img src='images/loading.gif'><br /> Loading</div>";
    }

    window_index++;
    windows_collection[window_index] = new Window({ className: "mac_os_x",
        title: window_name,
        width: form_width,
        height: form_height,
        //maxWidth:980, 
        //maxHeight:500, 
        showEffectOptions: { duration: 0.3 },
        hideEffectOptions: { duration: 0.3 },
        destroyOnClose: true,
        recenterAuto: false
    })
    windows_collection[window_index].showCenter();
    //windows_collection[window_index].getContent().innerHTML = content;
    windows_collection[window_index].setHTMLContent(content);
    return window_index;
}

/**
* method for submit form data in AJAX mode
*/
function saveAjax(form_element) {
    Dialog.info("<div class='default_input_form_layout' style='text-align:center'>Save In Progress<br />Please Wait ....</div>",
                { width: 250,
                    height: 100,
                    showProgress: true
                });

    form_element.action = form_element.action + '&ajax_mode=1';
    $(form_element).request({
        onComplete: function(transport) {
            Dialog.closeInfo();
            var json = transport.responseText.evalJSON();
            if (json.isError == true) {
                showDivPopup(json.errorContent, 'Error', 500, 200);
            } else {
                window.location.href = json.redirectURL;
            }
        }
    })
    return false;
}

/**
* method for togling table collapse and expand
*
* @param base_url	location of images folder
* @param layer_id	layer id used to show/hide the data
* @param img_id	image tag id used to set collapse/expand picture
*/
function toggleExpand(image_url, layer_id, img_id) {
    /*
    if (img_id != null) {
    var img_obj = document.getElementById(img_id);
    }
    var layer_obj = document.getElementById(layer_id);
    
    if (layer_obj.style.display == "") {
    if (img_id != null) {
    img_obj.src = image_url + "images/collapse.gif";
    }
    layer_obj.style.display = "none";
    } else {
    if (img_id != null) {
    img_obj.src = image_url + "images/expand.gif";
    }
    layer_obj.style.display = "";
    }
    */
    //Effect.toggle(layer_id, 'slide', {duration:0.3})
    toggleSlideEffect(layer_id);
    return false;
}

/**
* function copyLayer()
*
* @param destination_id	contain layer id where this item will be drawn
* @param source_id			contain template id will be used as reference
* @param row_prefix		contain row prefix for generating specific id
* @param row_prefix_id		contain row prefix to handle unique deletion
*/
function copyLayer(destination_id, source_id, row_prefix, row_prefix_id) {
    var NewItem = document.createElement("DIV");
    var Destination = document.getElementById(destination_id);
    NewItem.innerHTML = document.getElementById(source_id).innerHTML;
    NewItem.innerHTML = NewItem.innerHTML.replace(/_ID_/g, row_prefix_id);
    NewItem.innerHTML = NewItem.innerHTML.replace(/_N_/g, order_counter);
    order_counter++;
    NewItem.id = row_prefix + row_prefix_id;
    Destination.appendChild(NewItem);
}


/**
* function removeLayer()
*
* @param position_id	contain layer id where this item will be deleted
* @param row_prefix	contain layer id prefix
* @param row_prefix_id	contain layer id will be deleted
*/
function removeLayer(position_id, row_prefix, row_prefix_id) {
    var Position = document.getElementById(position_id);
    var DelItem = document.getElementById(row_prefix + row_prefix_id);
    Position.removeChild(DelItem);
}

/**
* method for set focus to a element in combobox
*/
function selectDefaultCombo(combo_id, default_value) {
    var combo_obj = document.getElementById(combo_id);
    for (var i = 0; i < combo_obj.length; i++) {
        if (combo_obj.options[i].value == default_value) {
            combo_obj.selectedIndex = i;
            return;
        }
    }
}

function selectRadioValue(radioname, selectedValue) {
	var radioObj = document.getElementsByName(radioname);
	
	if(!radioObj)
		return;
	
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == selectedValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == selectedValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

/**
* method for set focus a input element
*/
function setFocusElement(element_id) {
    document.getElementById(element_id).select();
}

/**
* method for make slide up effect at div element
*/
function slideUpEffect(element_id) {
    Effect.SlideUp(element_id, { duration: 0.3 });
}

/**
* method for make slide down effect at div element
*/
function slideDownEffect(element_id) {
    Effect.SlideDown(element_id, { duration: 0.3 });
}

/**
* method for make appear effect at div element
*/
function appearEffect(element_id) {
    Effect.Appear(element_id, { duration: 0.3 });
}

function toggleAppearEffect(element_id) {
    jQuery("#" + element_id).fadeToggle("0.3");
    //Effect.toggle(element_id, 'appear', { duration: 0.3 });
}

function toggleSlideEffect(element_id) {
    jQuery("#" + element_id).slideToggle("0.3");
	//Effect.toggle(element_id, 'slide', { duration: 0.3 });
}

function toggleBlindEffect(element_id) {
    Effect.toggle(element_id, 'blind', { duration: 0.3 });
}

function limitTextArea(textarea, limit)
{
	if (limit == undefined) {
		limit = 500;
	}
	
	var text = textarea.value; 
	var textlength = text.length;
	  
	if(textlength > limit)
	{
		textarea.value = text.substr(0,limit);
		return false;
	}
	else
	{
		return true;
	}
}

function syncCheckboxValue(element) {
	var hidden_element_id = element.id.replace('_' , ''); //only replace first char "_" with ""
	var hidden_element = document.getElementById(hidden_element_id);
	if (hidden_element != undefined) {
		if (element.checked == true) {
			hidden_element.value = 'true';
		} else {
			hidden_element.value = 'false';
		}
	}
}

function amnAutoComplete(input_el, param, select_func) {
    try {
        jQuery('#' + input_el).autocomplete("destroy");
    } catch (err) {

    }
    
    jQuery('#' + input_el).autocomplete({
        source: _BASE_PATH + '/AutoCompleteAjax/Index/?' + param,
        select: function(event, ui) {
            select_func(event, ui);
        }
    });
}

function amnBuildAutoComplete(input_el, 
							  table_name, 
							  key_field, 
							  value_field, 
							  key_property, 
							  value_property, 
							  select_func, 
							  backspace_func) {
    var url = "table=" + table_name +
              "&field=" + key_field +
              "&field=" + value_field +
              "&search_var=term" +
              "&search_field=" + value_field +
              "&json_key_prop=id" +
              "&json_value_field=" + key_field +
              "&json_key_prop=label" +
              "&json_value_field=" + value_field +
              "&json_key_prop=value" +
              "&json_value_field=" + value_field;

    amnAutoComplete(input_el, url, select_func);

    // for deletion
    jQuery('#' + input_el).keyup(function(event) {
        if (event.which == 8) {
            backspace_func();
            event.preventDefault();
        }
    });
}

function amnBuildAutoCompleteCriteria(input_el,
							  table_name,
							  key_field,
							  value_field,
							  search_field,
							  search_value,
							  select_func,
							  backspace_func) {
							  
    var url = "table=" + table_name +
              "&field=" + key_field +
              "&field=" + value_field +
              "&search_var=term" +
              "&search_field=" + value_field +
              "&json_key_prop=id" +
              "&json_value_field=" + key_field +
              "&json_key_prop=label" +
              "&json_value_field=" + value_field +
              "&json_key_prop=value" +
              "&json_value_field=" + value_field +
              "&criteria_field=" + search_field + 
              "&criteria_value=" + search_value;

    amnAutoComplete(input_el, url, select_func);
}